<template>
    <view class="addRefund">
        <uni-nav-bar fixed left-icon="left" :title="title" @clickLeft="backHandle" class="unibarS">
            <block slot="right">
                <text class="sub-btn" @click="submit">保存</text>
            </block>
        </uni-nav-bar>
        <!-- 主要内容 -->
        <view class="addRefund-content">
            <u--form labelPosition="left" :model="params" ref="uForm" labelWidth="70">
                <u-form-item class="item-box" label="关联客户" @click="SelectCus()" required borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view :class="!params.customerId ? 'item-temp-text-empty' : ''">{{
                            params.customerName || '点击选择' }}</view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="关联商品" required @click="selectGoods()" borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view v-if="params.commondityList.length">
                            已添加商品记录<text style="color: rgba(77, 172, 177, 1);">{{ params.commondityList.length }}</text>条
                        </view>
                        <view v-else class="item-temp-text-empty">点击选择</view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="退款金额" required borderBottom ref="item1">
                    <u--input v-model="params.refundAmount" border="none" placeholder="请填写"></u--input>
                </u-form-item>
                <u-form-item class="item-box" label="退款方式" required @click="showSelect('refundType')"
                    borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view :class="!params.refundType ? 'item-temp-text-empty' : ''">
                            <view v-if="params.refundType">
                                {{ params.refundType == 0? '全部退货' : params.refundType == 1 ? '部分退款' : '无需退回' }}
                            </view>
                            <view v-else>点击选择</view>
                        </view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="负责人员" required @click="selectHandle()"
                    borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view v-if="params.businessManagerId" class="avatar-box">
                            <u-avatar class="avatar" size="25" :src="params.avatar"></u-avatar>
                            <text>{{ params.businessManager }}</text>
                        </view>
                        <view v-else class="item-temp-text-empty">点击选择</view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="上传照片" @click="showPhoto()" borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view :class="!params.uploadAttachment ? 'item-temp-text-empty' : ''">
                            {{ params.uploadAttachment || '点击选择' }}
                        </view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="退款描述" labelPosition="top" borderBottom ref="item1">
                    <u--textarea v-model="params.refundDescription" border="false" placeholder="请输入退款描述" count
                        style="margin-top: 20rpx; background: #CCCCCC19;"></u--textarea>
                </u-form-item>
            </u--form>
        </view>
        <!-- 弹出选择菜单 -->
        <u-action-sheet :show="showActionSheet" :actions="actions" title="请选择" @close="showActionSheet = false"
            @select="sexSelect">
        </u-action-sheet>
        <!-- 选择跟进日期 -->
        <uni-calendar ref="calendar" class="uni-calendar--hook" :clear-date="true" :date="info.date"
            :insert="info.insert" @confirm="confirmCalendar" @close="closeCalendar" />
    </view>
</template>

<script>
import { convertToDict, upImage } from '@/common/utils'
export default {
    data() {
        return {
            title: '新增退款',
            showActionSheet: false,
            params: {
                refundAmount: null,
                customerName: null,
                customerId: null,
                businessManagerId: null,
                businessManager: null,
                avatar: null,
                uploadAttachment: null,
                commondityList: [],
                refundType: null,
                refundDescription: ''
            },

            // 弹出底部弹出菜单，展示的集合
            actions: [],
            count: 4,
            value: 2,
            // 存储属性，用于保存当前正在编辑的表单项
            tempPropName: null,
            showCalendar: false,
            info: {
                insert: false,
                selected: []
            },
            taskTaggingIndex: 1,
            refundTypeList: [
                { name: '全部退货', dictValue: '0' },
                { name: '部分退款', dictValue: '1' },
                { name: '无需退回', dictValue: '2' }
            ]
        }
    },
    onLoad(options) {
        this.bus_pay = JSON.parse(uni.getStorageSync('bus_pay_status'))
        this.bus_pay_status = convertToDict(this.bus_pay)

        if(options.id && options.type == 'edit') {
            this.title = '编辑退款'
            this.editID = options.id
            this.editType = true
            this.getDetails()
        }
    },

    methods: {
        getDetails() {
			this.$http.get('/app/refund/' + this.editID, {}).then(res => {
                console.log(res)
				if (res.code == 200) {
                    this.params = res.data
				} else {
					uni.$u.toast(res.msg)
				}
			})
		},
        // 显示选择器
        showSelect(propName) {
            // 退款方式
            if (propName == 'refundType') {
                this.actions = this.refundTypeList
            }
            this.tempPropName = propName
            this.showActionSheet = true
        },
        sexSelect(e) {
            this.params[this.tempPropName] = e.dictValue
        },
        // 选择客户
        SelectCus() {
            let that = this
            uni.navigateTo({
                url: '/pages/crm/customer/selectCustomer',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
                        that.params.customerId = data.data.id
                        that.params.customerName = data.data.customerName
                    },
                },
                success: function (res) {
					let obj = {
                        id: that.params.customerId,
                        customerName: that.params.customerName
                    }
                    res.eventChannel.emit('emitDataHandle', { data: obj })
                }
            });
        },
        // 选择业务员
        selectHandle() {
            let that = this
            uni.navigateTo({
                url: '/pages/crm/customer/selectSalesman',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
                        that.params.businessManagerId = data.data.userId
                        that.params.businessManager = data.data.userName
                        that.params.avatar = data.data.avatar
                    },
                },
                success: function (res) {
                    let obj = { 
                        userId: that.params.businessManagerId,
                        userName: that.params.businessManager,
                        avatar: that.params.avatar
                    }
                    res.eventChannel.emit('emitDataHandle', { data: obj })
                }
            });
        },
        // 关联商品
        selectGoods() {
            let that = this
            uni.navigateTo({
                url: '/pages/goods/relationGoods',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
                        let obj = JSON.parse(JSON.stringify(data.data))
                        that.params.commondityList = obj.list
                        // that.params.orderTotalAmount = obj.totalPrice
                    },
                },
                success: function (res) {
					// let obj = {}
                    res.eventChannel.emit('emitDataHandle', { data: that.params.commondityList })
                }
            });
        },
        showPhoto() {
            let that = this
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album'], //从相册选择
                success: function (res) {
                    upImage(res.tempFilePaths).then(res => {
                        console.log(res)
                        that.params.uploadAttachment = res[0]
                    })
                }
            });
        },
        // 打开日历
        openCalendar() {
            this.$refs.calendar.open()
        },
        // 确定日期
        confirmCalendar(e) {
            console.log(e)
            this.params.paymentDate = e.fulldate
        },
        // 关闭日历
        closeCalendar() { },
        submit() {
            // console.log(this.params)

            if(!this.params.customerId) return uni.$u.toast('请关联客户')
            if(!this.params.refundType) return uni.$u.toast('请选择退款方式')
            if(!this.params.commondityList.length) return uni.$u.toast('请关联商品')
            if(!this.params.refundAmount) return uni.$u.toast('请输入退款金额')
            if(!this.params.businessManagerId) return uni.$u.toast('请选择负责人员')

            let obj = JSON.parse(JSON.stringify(this.params))
            obj.commondityList = obj.commondityList.map(item => {
                return {
                    commondityId: item.commodityId,
                    commondityName: item.commodityName,
                    commondityUnit: item.contentUnit,
                    commondityPrice: item.unitPrice,
                    // refundNumber: item.commodityCode,
                    commondityBatch: '',
                    remark: item.remark,
                    commondityCount: item.quantity
                }
            })
            if(this.editType) {
                this.$http.put('/app/refund', obj).then(res => {
                    let data = res.data
                    if (data.code == 200) {
                        uni.showToast({ title: '成功', duration: 1000 });
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 1000)
                    } 
                })
            } else {
                this.$http.post('/app/refund', obj).then(res => {
                    let data = res.data
                    if (data.code == 200) {
                        uni.showToast({ title: '成功', duration: 1000 });
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 1000)
                    } 
                })
            }

        },
        backHandle() {
            uni.navigateBack()
        }
    }
}
</script>

<style lang="scss" scoped>

.addRefund-content {
    margin: 20rpx 0;
}

.item-box {
    border-radius: 16rpx;
    background: rgba(255, 255, 255, 1);
    padding: 0 32rpx;

    /deep/.u-input__content__field-wrapper__field {
        text-align: right !important;
    }

    .rate-box,
    .item-switch {
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }
}

.item-title {
    padding: 48rpx 32rpx 20rpx 32rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: rgba(12, 16, 25, 1);
}

.item-temp-box {
    text-align: right;
    width: 100%;
    font-size: 30rpx;
    flex: 1;
    width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    >view {
        // 超出隐藏
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}

.item-temp-text-empty {
    font-size: 30rpx;
    font-weight: 400;
    color: rgba(100, 117, 136, 1);
}

.avatar-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .tagging-item {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        margin-left: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}

.first-box {
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    background: rgba(255, 255, 255, 1);
    padding: 0 32rpx;
}

.task-item {
    margin-top: 20rpx;
}
</style>